/*
 * @Description:防抖和节流函数
 * @Author: StarChen
 * @Date: 2022-11-02 21:37:41
 * @LastEditTime: 2022-12-12 22:39:25
 * @LastEditors: StarChen
 */
// 防抖函数
// 立即防抖

/**
 *
 * @param {*} func abc
 * @param {*} wait 时间
 * @returns
 */
export function debounce(func, wait) {
  let timer = null;
  let context = this;
  let args = arguments;
  return function () {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(context, args);
    }, wait);
  };
}
// 非立即防抖
/**
 *
 * @param {function} func 要执行的函数
 * @param {string} wait 定时器时间
 */
export function debounce1(func, wait) {
  let timeout = null;
  let context = this;
  let args = arguments;
  return function () {
    if (timeout) clearTimeout(timeout);
    var callNow = !timeout;
    timeout = setTimeout(() => {
      timeout = null;
    }, wait);
    if (callNow) func.apply(context, args);
  };
}

// 节流
// 时间戳版
export function throttle(func, wait) {
  var previous = 0;
  return function () {
    var now = Date.now();
    var context = this;
    var args = arguments;
    if (now - previous > wait) {
      func.apply(context, args);
      previous = now;
    }
  };
}

// 定时器版
export function throttle1(func, wait) {
  var timeout;

  return function () {
    var context = this;
    var args = arguments;
    if (!timeout) {
      timeout = setTimeout(function () {
        timeout = null;
        func.apply(context, args);
      }, wait);
    }
  };
}
